package com.hutu.util;

public class HtmlEscaper {

    public static String escapeHtml(String input) {
        if (input == null) {
            return null;
        }

        StringBuilder out = new StringBuilder(input.length());
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            switch (c) {
                case '<':
                    out.append("&lt;");
                    break;
                case '>':
                    out.append("&gt;");
                    break;
                case '&':
                    out.append("&amp;");
                    break;
                case '"':
                    out.append("&quot;");
                    break;
                case '\'':
                    out.append("&#039;"); // 或者 "&apos;"，但并非所有浏览器都支持
                    break;
                // 如果需要转义其他字符，可以在这里添加更多的case
                default:
                    out.append(c);
            }
        }
        return out.toString();
    }

    public static void main(String[] args) {
        String input = "<html>This is a test with special characters: <, >, &, \", '.</html>";
        String escaped = escapeHtml(input);
        System.out.println(escaped);
    }
}
